<template>
  <div class="cost-container">
    <div class="cost-tabs">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 工时成本 -->
        <el-tab-pane label="工时成本" name="labor">
          <div class="tab-content">
            <div class="search-bar">
              <el-form :model="laborQueryParams" inline>
                <el-form-item label="项目名称">
                  <el-input
                    v-model="laborQueryParams.projectName"
                    placeholder="请输入项目名称"
                    style="width: 200px;"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="人员">
                  <el-input
                    v-model="laborQueryParams.empName"
                    placeholder="请输入人员姓名"
                    style="width: 200px;"
                    clearable
                  ></el-input>
                </el-form-item>
                <!-- 新增：日期范围查询 -->
                <el-form-item label="工作日期">
                  <el-date-picker
                    v-model="laborDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    style="width: 240px;"
                    @change="handleLaborDateChange"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleLaborSearch">搜索</el-button>
                  <el-button @click="handleLaborReset">重置</el-button>
                </el-form-item>
              </el-form>
              <el-button type="primary" @click="handleAddLabor" style="margin-left: auto;">添加工时</el-button>
            </div>

            <el-table :data="laborData" style="width: 100%" v-loading="laborLoading">
              <el-table-column prop="projectName" label="项目名称" width="200"></el-table-column>
              <el-table-column prop="empName" label="人员" width="120"></el-table-column>
              <el-table-column prop="workDate" label="工作日期" width="120"></el-table-column>
              <el-table-column prop="workHour" label="工时" width="80" align="center"></el-table-column>
              <el-table-column prop="hourlyWage" label="时薪" width="100" align="center">
                <template #default="{ row }">
                  ¥{{ row.hourlyWage }}
                </template>
              </el-table-column>
              <el-table-column prop="laborCost" label="工时成本" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ formatNumber(row.laborCost) }}
                </template>
              </el-table-column>
              <el-table-column prop="jobResponsibilities" label="工作内容" min-width="200"></el-table-column>
              <el-table-column label="操作" width="160" align="center">
                <template #default="{ row }">
                  <el-button size="small" type="primary" icon="Edit" @click="handleEditLabor(row)">编辑</el-button>
                  <el-button size="small" type="danger" icon="Delete" @click="handleDeleteLabor(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="laborQueryParams.pageNum"
                v-model:page-size="laborQueryParams.pageSize"
                :total="laborTotal"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleLaborSizeChange"
                @current-change="handleLaborPageChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 报销成本 -->
        <el-tab-pane label="报销成本" name="reimbursement">
          <div class="tab-content">
            <div class="search-bar">
              <el-form :model="reimbursementQueryParams" inline>
                <el-form-item label="项目名称">
                  <el-input
                    v-model="reimbursementQueryParams.projectName"
                    placeholder="请输入项目名称"
                    style="width: 200px;"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="报销类型">
                  <el-input
                    v-model="reimbursementQueryParams.reimbursementType"
                    placeholder="请输入报销类型"
                    style="width: 200px;"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select
                    v-model="reimbursementQueryParams.status"
                    placeholder="请选择状态"
                    style="width: 200px;"
                    clearable
                  >
                    <el-option label="待审批" value="待审批"></el-option>
                    <el-option label="已审批" value="已审批"></el-option>
                    <el-option label="已拒绝" value="已拒绝"></el-option>
                  </el-select>
                </el-form-item>
                <!-- 新增：日期范围查询 -->
                <el-form-item label="报销日期">
                  <el-date-picker
                    v-model="reimbursementDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    style="width: 240px;"
                    @change="handleReimbursementDateChange"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleReimbursementSearch">搜索</el-button>
                  <el-button @click="handleReimbursementReset">重置</el-button>
                </el-form-item>
              </el-form>
              <el-button type="primary" @click="handleAddReimbursement" style="margin-left: auto;">添加报销</el-button>
            </div>

            <el-table :data="reimbursementData" style="width: 100%" v-loading="reimbursementLoading">
              <el-table-column prop="projectName" label="项目名称" width="200"></el-table-column>
              <el-table-column prop="reimbursementType" label="报销类型" width="120"></el-table-column>
              <el-table-column prop="amount" label="金额" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ formatNumber(row.amount) }}
                </template>
              </el-table-column>
              <el-table-column prop="reimbursementDate" label="报销日期" width="120"></el-table-column>
              <el-table-column prop="reimbursementInstructions" label="报销说明" min-width="200"></el-table-column>
              <el-table-column prop="status" label="状态" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getReimbursementStatusType(row.status)">{{ row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" align="center">
                <template #default="{ row }">
                  <el-button size="small" type="primary" icon="Edit" @click="handleEditReimbursement(row)">编辑</el-button>
                  <el-button size="small" type="danger" icon="Delete" @click="handleDeleteReimbursement(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="reimbursementQueryParams.pageNum"
                v-model:page-size="reimbursementQueryParams.pageSize"
                :total="reimbursementTotal"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleReimbursementSizeChange"
                @current-change="handleReimbursementPageChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 付款成本 -->
        <el-tab-pane label="付款成本" name="payment">
          <div class="tab-content">
            <div class="search-bar">
              <el-form :model="paymentQueryParams" inline>
                <el-form-item label="项目名称">
                  <el-input
                    v-model="paymentQueryParams.projectName"
                    placeholder="请输入项目名称"
                    style="width: 200px;"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="付款类型">
                  <el-input
                    v-model="paymentQueryParams.paymentType"
                    placeholder="请输入付款类型"
                    style="width: 200px;"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select
                    v-model="paymentQueryParams.status"
                    placeholder="请选择状态"
                    style="width: 200px;"
                    clearable
                  >
                    <el-option label="待付款" value="待付款"></el-option>
                    <el-option label="已付款" value="已付款"></el-option>
                    <el-option label="已取消" value="已取消"></el-option>
                  </el-select>
                </el-form-item>
                <!-- 新增：日期范围查询 -->
                <el-form-item label="付款日期">
                  <el-date-picker
                    v-model="paymentDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    style="width: 240px;"
                    @change="handlePaymentDateChange"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handlePaymentSearch">搜索</el-button>
                  <el-button @click="handlePaymentReset">重置</el-button>
                </el-form-item>
              </el-form>
              <el-button type="primary" @click="handleAddPayment" style="margin-left: auto;">添加付款</el-button>
            </div>

            <el-table :data="paymentData" style="width: 100%" v-loading="paymentLoading">
              <el-table-column prop="projectName" label="项目名称" width="200"></el-table-column>
              <el-table-column prop="paymentType" label="付款类型" width="120"></el-table-column>
              <el-table-column prop="amount" label="金额" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ formatNumber(row.amount) }}
                </template>
              </el-table-column>
              <el-table-column prop="paymentDate" label="付款日期" width="120"></el-table-column>
              <el-table-column prop="paymentInstructions" label="付款说明" min-width="200"></el-table-column>
              <el-table-column prop="status" label="状态" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getPaymentStatusType(row.status)">{{ row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" align="center">
                <template #default="{ row }">
                  <el-button size="small" type="primary" icon="Edit" @click="handleEditPayment(row)">编辑</el-button>
                  <el-button size="small" type="danger" icon="Delete" @click="handleDeletePayment(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="paymentQueryParams.pageNum"
                v-model:page-size="paymentQueryParams.pageSize"
                :total="paymentTotal"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePaymentSizeChange"
                @current-change="handlePaymentPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 工时成本对话框 -->
    <el-dialog :title="laborDialogTitle" :visible.sync="laborOpen" width="600px" append-to-body>
      <el-form :model="laborForm" :rules="laborRules" ref="laborFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-select v-model="laborForm.projectName" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.name"
              :value="project.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员" prop="empName">
          <el-input v-model="laborForm.empName" placeholder="请输入人员姓名"></el-input>
        </el-form-item>
        <el-form-item label="工作日期" prop="workDate">
          <el-date-picker
            v-model="laborForm.workDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="工时" prop="workHour">
          <el-input-number v-model="laborForm.workHour" :min="0" :precision="1" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="时薪" prop="hourlyWage">
          <el-input-number v-model="laborForm.hourlyWage" :min="0" :precision="2" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="工作内容" prop="jobResponsibilities">
          <el-input v-model="laborForm.jobResponsibilities" type="textarea" :rows="3" placeholder="请输入工作内容"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="laborCancel">取消</el-button>
        <el-button type="primary" @click="submitLaborForm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 报销成本对话框 -->
    <el-dialog :title="reimbursementDialogTitle" :visible.sync="reimbursementOpen" width="600px" append-to-body>
      <el-form :model="reimbursementForm" :rules="reimbursementRules" ref="reimbursementFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-select v-model="reimbursementForm.projectName" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.name"
              :value="project.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销类型" prop="reimbursementType">
          <el-input
            v-model="reimbursementForm.reimbursementType"
            placeholder="请输入报销类型"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="reimbursementForm.amount" :min="0" :precision="2" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="报销日期" prop="reimbursementDate">
          <el-date-picker
            v-model="reimbursementForm.reimbursementDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="报销说明" prop="reimbursementInstructions">
          <el-input v-model="reimbursementForm.reimbursementInstructions" type="textarea" :rows="3"
                    placeholder="请输入报销说明"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="reimbursementForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待审批" value="待审批"></el-option>
            <el-option label="已审批" value="已审批"></el-option>
            <el-option label="已拒绝" value="已拒绝"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reimbursementCancel">取消</el-button>
        <el-button type="primary" @click="submitReimbursementForm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 付款成本对话框 -->
    <el-dialog :title="paymentDialogTitle" :visible.sync="paymentOpen" width="600px" append-to-body>
      <el-form :model="paymentForm" :rules="paymentRules" ref="paymentFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-select v-model="paymentForm.projectName" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.name"
              :value="project.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款类型" prop="paymentType">
          <el-input
            v-model="paymentForm.paymentType"
            placeholder="请输入付款类型"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="paymentForm.amount" :min="0" :precision="2" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="付款日期" prop="paymentDate">
          <el-date-picker
            v-model="paymentForm.paymentDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="付款说明" prop="paymentInstructions">
          <el-input v-model="paymentForm.paymentInstructions" type="textarea" :rows="3"
                    placeholder="请输入付款说明"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="paymentForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待付款" value="待付款"></el-option>
            <el-option label="已付款" value="已付款"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paymentCancel">取消</el-button>
        <el-button type="primary" @click="submitPaymentForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as costApi from '@/api/cost/cost'

export default {
  name: 'ProjectCost',
  data() {
    return {
      activeTab: 'labor',

      // 加载状态
      laborLoading: false,
      reimbursementLoading: false,
      paymentLoading: false,

      // 查询参数
      laborQueryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        empName: '',
        startDate: '',  // 新增：开始日期
        endDate: ''     // 新增：结束日期
      },
      reimbursementQueryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        reimbursementType: '',
        status: '',
        startDate: '',  // 新增：开始日期
        endDate: ''     // 新增：结束日期
      },
      paymentQueryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        paymentType: '',
        status: '',
        startDate: '',  // 新增：开始日期
        endDate: ''     // 新增：结束日期
      },

      // 日期范围选择器数据
      laborDateRange: [],           // 工时日期范围
      reimbursementDateRange: [],   // 报销日期范围
      paymentDateRange: [],         // 付款日期范围

      // 数据
      laborData: [],
      reimbursementData: [],
      paymentData: [],

      // 总数
      laborTotal: 0,
      reimbursementTotal: 0,
      paymentTotal: 0,

      // 项目列表 - 初始为空数组，将从后端获取
      projectList: [],

      // 对话框状态
      laborOpen: false,
      reimbursementOpen: false,
      paymentOpen: false,

      // 表单数据
      laborForm: {
        id: null,
        projectName: '',
        empName: '',
        workDate: '',
        workHour: 0,
        hourlyWage: 0,
        jobResponsibilities: ''
      },

      reimbursementForm: {
        id: null,
        projectName: '',
        reimbursementType: '',
        amount: 0,
        reimbursementDate: '',
        reimbursementInstructions: '',
        status: '待审批'
      },

      paymentForm: {
        id: null,
        projectName: '',
        paymentType: '',
        amount: 0,
        paymentDate: '',
        paymentInstructions: '',
        status: '待付款'
      },

      // 表单验证规则
      laborRules: {
        projectName: [{ required: true, message: '请选择项目', trigger: 'change' }],
        empName: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
        workDate: [{ required: true, message: '请选择工作日期', trigger: 'change' }],
        workHour: [{ required: true, message: '请输入工时', trigger: 'blur' }],
        hourlyWage: [{ required: true, message: '请输入时薪', trigger: 'blur' }]
      },

      reimbursementRules: {
        projectName: [{ required: true, message: '请选择项目', trigger: 'change' }],
        reimbursementType: [{ required: true, message: '请输入报销类型', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        reimbursementDate: [{ required: true, message: '请选择报销日期', trigger: 'change' }]
      },

      paymentRules: {
        projectName: [{ required: true, message: '请选择项目', trigger: 'change' }],
        paymentType: [{ required: true, message: '请输入付款类型', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        paymentDate: [{ required: true, message: '请选择付款日期', trigger: 'change' }]
      }
    }
  },

  computed: {
    // 对话框标题
    laborDialogTitle() {
      return this.laborForm.id ? '编辑工时' : '添加工时'
    },

    reimbursementDialogTitle() {
      return this.reimbursementForm.id ? '编辑报销' : '添加报销'
    },

    paymentDialogTitle() {
      return this.paymentForm.id ? '编辑付款' : '添加付款'
    }
  },

  mounted() {
    this.loadLaborData()
    this.loadProjectList() // 新增：加载项目列表
  },

  methods: {
    // 格式化数字
    formatNumber(num) {
      if (!num) return 0
      return Number(num).toLocaleString()
    },

    // 加载项目列表
    async loadProjectList() {
      try {
        const response = await costApi.getProjectList()
        if (response.code === 200) {
          this.projectList = response.data || []
          console.log('加载的项目列表:', this.projectList)
        } else {
          this.$message.error(response.message || '加载项目列表失败')
          this.projectList = []
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
        this.projectList = []
        this.$message.error('加载项目列表失败')
      }
    },

    // 日期范围变化处理
    handleLaborDateChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.laborQueryParams.startDate = dateRange[0]
        this.laborQueryParams.endDate = dateRange[1]
      } else {
        this.laborQueryParams.startDate = ''
        this.laborQueryParams.endDate = ''
      }
    },

    handleReimbursementDateChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.reimbursementQueryParams.startDate = dateRange[0]
        this.reimbursementQueryParams.endDate = dateRange[1]
      } else {
        this.reimbursementQueryParams.startDate = ''
        this.reimbursementQueryParams.endDate = ''
      }
    },

    handlePaymentDateChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.paymentQueryParams.startDate = dateRange[0]
        this.paymentQueryParams.endDate = dateRange[1]
      } else {
        this.paymentQueryParams.startDate = ''
        this.paymentQueryParams.endDate = ''
      }
    },

    // 标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name
      if (tab.name === 'labor' && this.laborData.length === 0) {
        this.loadLaborData()
      } else if (tab.name === 'reimbursement' && this.reimbursementData.length === 0) {
        this.loadReimbursementData()
      } else if (tab.name === 'payment' && this.paymentData.length === 0) {
        this.loadPaymentData()
      }
    },

    // 工时相关方法
    async loadLaborData() {
      this.laborLoading = true
      try {
        const response = await costApi.listLaborCost(this.laborQueryParams)
        this.laborData = response.data.rows || []
        this.laborTotal = response.data.total || 0
      } catch (error) {
        console.error('加载工时数据失败:', error)
        this.laborData = []
        this.laborTotal = 0
      } finally {
        this.laborLoading = false
      }
    },

    handleLaborSearch() {
      this.laborQueryParams.pageNum = 1
      this.loadLaborData()
    },

    handleLaborReset() {
      this.laborQueryParams = {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        empName: '',
        startDate: '',
        endDate: ''
      }
      this.laborDateRange = []
      this.loadLaborData()
    },

    handleLaborSizeChange(size) {
      this.laborQueryParams.pageSize = size
      this.laborQueryParams.pageNum = 1
      this.loadLaborData()
    },

    handleLaborPageChange(page) {
      this.laborQueryParams.pageNum = page
      this.loadLaborData()
    },

    handleAddLabor() {
      this.laborReset()
      this.laborOpen = true
    },

    // 工时编辑
    async handleEditLabor(row) {
      const _id = row.id
      if (!_id) return this.$message.error("请选择数据")

      // 先重置表单
      this.laborReset()

      try {
        const response = await costApi.getLaborCost(_id)
        console.log("获取工时详情响应:", response)
        const data = response.data || {}

        // 使用 $nextTick 确保 DOM 更新后再填充数据
        this.$nextTick(() => {
          this.laborForm = {
            id: data.id || null,
            projectName: data.projectName || "",
            empName: data.empName || "",
            workDate: data.workDate || "",
            workHour: data.workHour || 0,
            hourlyWage: data.hourlyWage || 0,
            jobResponsibilities: data.jobResponsibilities || ""
          }

          console.log("填充后的工时表单数据:", this.laborForm)
        })

        this.laborOpen = true
      } catch (error) {
        console.error("获取工时详情失败:", error)
        this.$message.error("获取详情失败")
      }
    },

    async handleDeleteLabor(row) {
      try {
        await this.$confirm('确定要删除这条工时记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await costApi.delLaborCost([row.id])
        this.$message.success('删除成功')
        this.loadLaborData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async submitLaborForm() {
      try {
        await this.$refs.laborFormRef.validate()

        if (this.laborForm.id) {
          await costApi.updateLaborCost(this.laborForm.id, this.laborForm)
          this.$message.success('更新成功')
        } else {
          await costApi.addLaborCost(this.laborForm)
          this.$message.success('添加成功')
        }

        this.laborOpen = false
        this.loadLaborData()
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    laborCancel() {
      this.laborOpen = false
      this.laborReset()
    },

    laborReset() {
      this.laborForm = {
        id: null,
        projectName: '',
        empName: '',
        workDate: '',
        workHour: 0,
        hourlyWage: 0,
        jobResponsibilities: ''
      }
      this.$refs.laborFormRef && this.$refs.laborFormRef.resetFields()
    },

    // 报销相关方法
    async loadReimbursementData() {
      this.reimbursementLoading = true
      try {
        const response = await costApi.listReimbursementCost(this.reimbursementQueryParams)
        this.reimbursementData = response.data.rows || []
        this.reimbursementTotal = response.data.total || 0
      } catch (error) {
        console.error('加载报销数据失败:', error)
        this.reimbursementData = []
        this.reimbursementTotal = 0
      } finally {
        this.reimbursementLoading = false
      }
    },

    handleReimbursementSearch() {
      this.reimbursementQueryParams.pageNum = 1
      this.loadReimbursementData()
    },

    handleReimbursementReset() {
      this.reimbursementQueryParams = {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        reimbursementType: '',
        status: '',
        startDate: '',
        endDate: ''
      }
      this.reimbursementDateRange = []
      this.loadReimbursementData()
    },

    handleReimbursementSizeChange(size) {
      this.reimbursementQueryParams.pageSize = size
      this.reimbursementQueryParams.pageNum = 1
      this.loadReimbursementData()
    },

    handleReimbursementPageChange(page) {
      this.reimbursementQueryParams.pageNum = page
      this.loadReimbursementData()
    },

    handleAddReimbursement() {
      this.reimbursementReset()
      this.reimbursementOpen = true
    },

    // 报销编辑
    async handleEditReimbursement(row) {
      const _id = row.id
      if (!_id) return this.$message.error("请选择数据")

      this.reimbursementReset()

      try {
        const response = await costApi.getReimbursementCost(_id)
        console.log("获取报销详情响应:", response)
        const data = response.data || {}

        this.$nextTick(() => {
          this.reimbursementForm = {
            id: data.id || null,
            projectName: data.projectName || "",
            reimbursementType: data.reimbursementType || "",
            amount: data.amount || 0,
            reimbursementDate: data.reimbursementDate || "",
            reimbursementInstructions: data.reimbursementInstructions || "",
            status: data.status || "待审批"
          }

          console.log("填充后的报销表单数据:", this.reimbursementForm)
        })

        this.reimbursementOpen = true
      } catch (error) {
        console.error("获取报销详情失败:", error)
        this.$message.error("获取详情失败")
      }
    },

    async handleDeleteReimbursement(row) {
      try {
        await this.$confirm('确定要删除这条报销记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await costApi.delReimbursementCost([row.id])
        this.$message.success('删除成功')
        this.loadReimbursementData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async submitReimbursementForm() {
      try {
        await this.$refs.reimbursementFormRef.validate()

        if (this.reimbursementForm.id) {
          await costApi.updateReimbursementCost(this.reimbursementForm.id, this.reimbursementForm)
          this.$message.success('更新成功')
        } else {
          await costApi.addReimbursementCost(this.reimbursementForm)
          this.$message.success('添加成功')
        }

        this.reimbursementOpen = false
        this.loadReimbursementData()
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    reimbursementCancel() {
      this.reimbursementOpen = false
      this.reimbursementReset()
    },

    reimbursementReset() {
      this.reimbursementForm = {
        id: null,
        projectName: '',
        reimbursementType: '',
        amount: 0,
        reimbursementDate: '',
        reimbursementInstructions: '',
        status: '待审批'
      }
      this.$refs.reimbursementFormRef && this.$refs.reimbursementFormRef.resetFields()
    },

    // 付款相关方法
    async loadPaymentData() {
      this.paymentLoading = true
      try {
        const response = await costApi.listPaymentCost(this.paymentQueryParams)
        this.paymentData = response.data.rows || []
        this.paymentTotal = response.data.total || 0
      } catch (error) {
        console.error('加载付款数据失败:', error)
        this.paymentData = []
        this.paymentTotal = 0
      } finally {
        this.paymentLoading = false
      }
    },

    handlePaymentSearch() {
      this.paymentQueryParams.pageNum = 1
      this.loadPaymentData()
    },

    handlePaymentReset() {
      this.paymentQueryParams = {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        paymentType: '',
        status: '',
        startDate: '',
        endDate: ''
      }
      this.paymentDateRange = []
      this.loadPaymentData()
    },

    handlePaymentSizeChange(size) {
      this.paymentQueryParams.pageSize = size
      this.paymentQueryParams.pageNum = 1
      this.loadPaymentData()
    },

    handlePaymentPageChange(page) {
      this.paymentQueryParams.pageNum = page
      this.loadPaymentData()
    },

    handleAddPayment() {
      this.paymentReset()
      this.paymentOpen = true
    },

    // 付款编辑
    async handleEditPayment(row) {
      const _id = row.id
      if (!_id) return this.$message.error("请选择数据")

      this.paymentReset()

      try {
        const response = await costApi.getPaymentCost(_id)
        console.log("获取付款详情响应:", response)
        const data = response.data || {}

        this.$nextTick(() => {
          this.paymentForm = {
            id: data.id || null,
            projectName: data.projectName || "",
            paymentType: data.paymentType || "",
            amount: data.amount || 0,
            paymentDate: data.paymentDate || "",
            paymentInstructions: data.paymentInstructions || "",
            status: data.status || "待付款"
          }

          console.log("填充后的付款表单数据:", this.paymentForm)
        })

        this.paymentOpen = true
      } catch (error) {
        console.error("获取付款详情失败:", error)
        this.$message.error("获取详情失败")
      }
    },

    async handleDeletePayment(row) {
      try {
        await this.$confirm('确定要删除这条付款记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await costApi.delPaymentCost([row.id])
        this.$message.success('删除成功')
        this.loadPaymentData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async submitPaymentForm() {
      try {
        await this.$refs.paymentFormRef.validate()

        if (this.paymentForm.id) {
          await costApi.updatePaymentCost(this.paymentForm.id, this.paymentForm)
          this.$message.success('更新成功')
        } else {
          await costApi.addPaymentCost(this.paymentForm)
          this.$message.success('添加成功')
        }

        this.paymentOpen = false
        this.loadPaymentData()
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    paymentCancel() {
      this.paymentOpen = false
      this.paymentReset()
    },

    paymentReset() {
      this.paymentForm = {
        id: null,
        projectName: '',
        paymentType: '',
        amount: 0,
        paymentDate: '',
        paymentInstructions: '',
        status: '待付款'
      }
      this.$refs.paymentFormRef && this.$refs.paymentFormRef.resetFields()
    },

    // 状态类型
    getReimbursementStatusType(status) {
      const statusMap = {
        '待审批': 'warning',
        '已审批': 'success',
        '已拒绝': 'danger'
      }
      return statusMap[status] || 'info'
    },

    getPaymentStatusType(status) {
      const statusMap = {
        '待付款': 'warning',
        '已付款': 'success',
        '已取消': 'danger'
      }
      return statusMap[status] || 'info'
    }
  }
}
</script>

<style lang="scss" scoped>
.cost-container {
  padding: 24px;
  background: #ffffff;
  min-height: calc(100vh - 84px);
}

.cost-tabs {
  .el-tabs__content {
    padding-top: 24px;
  }
}

.tab-content {
  .search-bar {
    margin-bottom: 24px;
    display: flex;
    align-items: flex-start;
    gap: 16px;

    .el-form {
      flex: 1;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;

    .el-form {
      width: 100%;
    }
  }
}
</style>
